/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-05 08:41:15
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 16:35:58
 * @FilePath: /operator-manager/src/pages/AccountAccessManage/AccountManage/index.tsx
 * @Description: 账号管理
 */
import AccessButton, {
  BtnAccessEnum,
  accessBtnMap,
} from '@/components/AccessBtn';
import { accountStatusUpdate, getAccountList } from '@/services';
import {
  accountType,
  defaultPagination,
  defaultTableData,
} from '@/utils/globalConstants';
import { ProFormText, QueryFilter } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import type { FormInstance } from 'antd';
import { Button, Popconfirm, Space, Table, message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useEffect, useRef, useState } from 'react';
import AccountCreate from '../components/AccountCreate';
import AccountEdit from '../components/AccountEdit';
import { accountStatusMap } from '../constants';
import {
  AccountStatusEnum,
  AccountTableDataType,
  AccountTableEnum,
} from '../type.d';

export default function EmployeeManagePage() {
  const accountSearchRef = useRef<FormInstance>();
  const [tableData, setTableData] = useState({ ...defaultTableData });
  const [paginationCurrent, setPagination] = useState({ ...defaultPagination });
  const tableAreaClass = useEmotionCss(() => {
    return {
      padding: '20px',
    };
  });
  //获取商家订单的列表数据
  const fetchAccountList = async (params = {}) => {
    const searchValues = accountSearchRef?.current?.getFieldsValue() ?? {};
    const { page: pageNo, pageSize } = paginationCurrent;
    const searchParams = {
      pageNo,
      pageSize,
      ...searchValues,
      ...params,
      type: accountType, // 莫名其妙的参数，不知道为什么非得加
    };
    console.log('进行搜索的条件为', searchParams);
    const result = await getAccountList(searchParams);
    const { dataList, totalResult } = result?.data ?? {};
    setTableData({
      dataList,
      total: totalResult,
    });
  };
  //修改账号状态
  const handleUpdateStatus = (data: Record<string, string | number>) => {
    accountStatusUpdate({ data }).then((res) => {
      if (res?.success) {
        //修改成功,刷新列表
        message.success('状态更新成功');
        fetchAccountList();
      }
    });
  };
  const columns: ColumnsType<AccountTableDataType> = [
    {
      title: '姓名',
      dataIndex: AccountTableEnum.NAME,
      width: 150,
    },
    {
      title: '手机号',
      dataIndex: AccountTableEnum.PHONE,
      width: 150,
    },
    {
      title: '角色',
      dataIndex: AccountTableEnum.ROLE,
      width: 150,
    },
    {
      title: '状态',
      dataIndex: AccountTableEnum.STATUS,
      width: 150,
      render: (value) => {
        const showItem = accountStatusMap.get(value);
        return showItem ? (
          <span style={{ color: showItem?.color }}>{showItem?.text}</span>
        ) : (
          '-'
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 150,
      render: (_, record: AccountTableDataType) => {
        const accountStatus = record[AccountTableEnum.STATUS];
        return (
          <Space>
            <AccessButton
              accessKey={accessBtnMap.get(BtnAccessEnum.ACCOUNT_EDIT) as string}
            >
              <AccountEdit
                formKey={record.id}
                initValues={record}
                successCallback={fetchAccountList}
              />
            </AccessButton>
            {accountStatus === AccountStatusEnum.FORBIDDEN ? (
              <AccessButton
                accessKey={
                  accessBtnMap.get(BtnAccessEnum.ACCOUNT_OPEN) as string
                }
              >
                <Popconfirm
                  title="确定要开启该账号吗？"
                  onConfirm={() =>
                    handleUpdateStatus({ id: record.id, status: 1 })
                  }
                >
                  <Button type="link" style={{ color: '#080' }}>
                    开启
                  </Button>
                </Popconfirm>
              </AccessButton>
            ) : null}
            {accountStatus === AccountStatusEnum.NORMAL ? (
              <AccessButton
                accessKey={
                  accessBtnMap.get(BtnAccessEnum.ACCOUNT_FORBIDDEN) as string
                }
              >
                <Popconfirm
                  title="确定要禁用该账号吗？"
                  onConfirm={() =>
                    handleUpdateStatus({ id: record.id, status: 0 })
                  }
                >
                  <Button type="link" style={{ color: '#f00' }}>
                    禁用
                  </Button>
                </Popconfirm>
              </AccessButton>
            ) : null}
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    fetchAccountList();
  }, []);

  return (
    <div>
      <QueryFilter
        defaultCollapsed
        split
        formRef={accountSearchRef}
        submitter={{
          render: (_, dom) => {
            return dom.reverse();
          },
        }}
        onFinish={async (values) => {
          fetchAccountList({ ...values });
        }}
        onReset={() => {
          fetchAccountList();
        }}
      >
        <ProFormText
          name={AccountTableEnum.PHONE}
          label="手机号"
          key="account-search-input"
        />
      </QueryFilter>

      <div className={tableAreaClass}>
        <AccessButton
          accessKey={accessBtnMap.get(BtnAccessEnum.ACCOUNT_ADD) as string}
        >
          <AccountCreate successCallback={fetchAccountList} />
        </AccessButton>
        <Table
          rowKey="id"
          dataSource={tableData.dataList}
          columns={columns}
          scroll={{ x: 'max-width' }}
          style={{ marginTop: '20px' }}
          pagination={{
            pageSize: paginationCurrent.pageSize,
            current: paginationCurrent.page,
            pageSizeOptions: [20, 50, 100],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: (page, pageSize) => {
              setPagination({ page, pageSize });
              fetchAccountList({ page, pageSize });
            },
          }}
        />
      </div>
    </div>
  );
}
